package com.bjc.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: nettypro
 * @description: BIO
 * @author: bjc
 * @create: 2021-09-02 20:43
 */
public class BIOServer {

    /**
     * 创建一个线程池
     * 如果有客户端连接，就创建一个线程 与之通讯
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建ServerSocket
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(6666);
            System.out.println("服务器启动了");
            while (true){
                System.out.println("等待连接");
                //监听 等待客户端连接
                final Socket socket = serverSocket.accept();
                System.out.println("连接到一个客户端");
                //创建一个线程与之通讯
                newCachedThreadPool.execute(()->{
                    //和客户端通讯
                    handler(socket);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void handler(Socket socket){
        System.out.println("线程信息：id="+Thread.currentThread().getId()+",名称:"+Thread.currentThread().getName());
        try {
            byte[] bytes = new byte[1024];
            //通过socket  获取流
            InputStream inputStream = socket.getInputStream();
            //循环的读取客户端发送的数据
            while (true){
                System.out.println("线程信息：id="+Thread.currentThread().getId()+",名称:"+Thread.currentThread().getName());

                System.out.println("----------read---------");
                int read = inputStream.read(bytes);
                if (read!=-1){
                    System.out.println(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
